package com.houdoudou.customer;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.houdoudou.bean.Machine;
import com.houdoudou.bean.Order;
import com.houdoudou.bean.OrderProduct;
import com.houdoudou.bean.Refund;
import com.houdoudou.customer.buy.ChoosePayAct;
import com.houdoudou.customer.buy.OrderDetailAct;
import com.houdoudou.customer.common.AsynImageLoader;
import com.houdoudou.customer.common.CommonFunction;
import com.houdoudou.customer.common.Constant;
import com.houdoudou.customer.common.DateTimeFunction;
import com.houdoudou.customer.common.HorizontalListView;
import com.houdoudou.customer.common.UniversalHttpPost;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class FrgOrderOfActMain extends Fragment {


	ListView orderList;
	ProgressBar progres;
	Button repull;
	LinearLayout lt_pullfailed;
	TextView pull_result;
	AsynImageLoader imageLoader;
	JSONArray ordersJA= new JSONArray();

	public OrderListAdapter orderListAdapter;
	public static boolean  needPullOrder=true;
	
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {  
		
	       @Override  
	       public void onReceive(Context context, Intent intent) {  
       // TODO Auto-generated method stub  
	    	   String orderJOStr= intent.getExtras().getString("order");
	    	  JSONObject orderJO= JSONObject.fromObject(orderJOStr);	
	    	  int id=orderJO.getInt(Order.ID);
	    	  System.out.println("FrgOrderOfActMain broadcastReceiver order id="+id);
		       for(int i=0;i< ordersJA.size();i++){
		    	   if(ordersJA.getJSONObject(i).getInt(Order.ID)==id){
		    		   ordersJA.set(i, orderJO);
		    		   orderListAdapter.notifyDataSetChanged();
		    		   return;
		    	   }  } 
   }  
	   }; 
	   
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		//return super.onCreateView(inflater, container, savedInstanceState);
		View view=inflater.inflate(R.layout.frg_order_act_main, container, false);
		imageLoader= new AsynImageLoader(getActivity());
        orderList= (ListView) view.findViewById(R.id.list_order_frgorder_actmain);
      
        orderListAdapter= new OrderListAdapter(getActivity());
        orderList.setAdapter(orderListAdapter);
        
        progres= (ProgressBar) view.findViewById(R.id.prgs_frgorder_actmain);
        pull_result= (TextView) view.findViewById(R.id.tv_pullresult_frgorder_actmain);
        lt_pullfailed= (LinearLayout) view.findViewById(R.id.lt_pullfailed_frgorder_actmain);
        repull= (Button) view.findViewById(R.id.btn_repull_frgorder_actmain);
        progres.setVisibility(View.GONE);
        lt_pullfailed.setVisibility(View.GONE);   
        repull.setOnClickListener(new View.OnClickListener() {	
			@Override
			public void onClick(View v) { 
				pull_order();
			}
		});     
        IntentFilter filter = new IntentFilter(ChoosePayAct.ACTION_ORDER_CHANGED);  
        getActivity().registerReceiver(broadcastReceiver, filter);  
		return view;
	}
	
	  
	   
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(needPullOrder) pull_order();
	}
	
	

	 private void    pull_order(){		
		 if(Constant.customerJO==null){return ;}
		    progres.setVisibility(View.VISIBLE);
			orderList.setVisibility(View.GONE);
			lt_pullfailed.setVisibility(View.GONE);
			String[] params= new String[3];
         params[0]=Constant.BaseUrl+Constant.CustomerUrl;
         params[1]="pullLatestOrder"; //PostCod
         JSONObject jsonData=new JSONObject();
         jsonData.put("customer", Constant.customerJO);
        params[2]=jsonData.toString();
      new HttpPostTaskforPollLatestOrder().execute(params);
     }
	 
   

   class OrderListAdapter extends BaseAdapter {
	   
	
    private LayoutInflater layoutInflater;  
    private Context context;  
    
   public OrderListAdapter(Context context) {
		super();
		
		this.context = context;
	    this.layoutInflater=LayoutInflater.from(context); 
	}


  final class Zujian{  
    public TextView supplier,orderId,dateTimeAA,orderMoney,orderState;  
    public  Button  see;
    public HorizontalListView picList;
  }   //end of Zujian

      @Override 
    public int getCount() {
	// TODO Auto-generated method stub
	
	 return ordersJA.size();  
}

   @Override
  public Object getItem(int position) {
	// TODO Auto-generated method stub
	 return ordersJA.getJSONObject(position);  
}

  @Override
  public long getItemId(int position) {
	// TODO Auto-generated method stub
	return position; 
}

  @Override
  public View getView(int position, View  convertView, ViewGroup parent) {
	// TODO Auto-generated method stub
	final int selectID = position;   
	 Zujian zj=null;  
        if(convertView==null){  
            zj=new Zujian();  
            //获得组件，实例化组件  
            convertView=layoutInflater.inflate(R.layout.list_order, null);    
        //    zj.supplier= (TextView) convertView.findViewById(R.id.tv_supplier_listorder);
            zj.orderId=(TextView) convertView.findViewById(R.id.tv_orderid_listorder);
            zj.orderMoney=(TextView) convertView.findViewById(R.id.tv_money_listorder);
            zj.orderState=(TextView) convertView.findViewById(R.id.tv_orderstate_listorder);
            zj.picList= (HorizontalListView) convertView.findViewById(R.id.hlistview_list_order);
            zj.dateTimeAA=(TextView) convertView.findViewById(R.id.tv_datetimeaa_listorder);
            zj.see= (Button) convertView.findViewById(R.id.btn_see_listorder);
            convertView.setTag(zj);  
            System.out.println("position----"+selectID+"------inflated");
        }else{   System.out.println("position----"+selectID+"-------not inflated");
            zj=(Zujian)convertView.getTag();  
        }  			  
        //绑定数据  
     //   zj.supplier.setText("商家热线："+ordersJA.getJSONObject(selectID).getString(Order.SERVICETELNUM));
        zj.orderId.setText("订单号："+ordersJA.getJSONObject(selectID).getLong(Order.ID));
        zj.orderMoney.setText("总金额："+ordersJA.getJSONObject(selectID).getDouble(Order.MONEYCU)+"   总数量："+ordersJA.getJSONObject(selectID).getInt(Order.PRODUCTNUM));
        String dateTimeAA=ordersJA.getJSONObject(selectID).getString(Order.DATETIMEAA);
        
        try {String wordDateTimeAA=DateTimeFunction.transWordDateFormat(dateTimeAA);
        	zj.dateTimeAA.setText("送达时间："+wordDateTimeAA);
		} catch (Exception e) {e.printStackTrace();	}
        String stateWords="";
        stateWords ="订单："+CommonFunction.spellOrderStateWord(ordersJA.getJSONObject(selectID).getInt(Order.STATE));
        if(ordersJA.getJSONObject(selectID).getInt(Order.ISREFUND)!=1){
       int refundSate=ordersJA.getJSONObject(selectID).getJSONObject("refund").getInt(Refund.STATE);
       stateWords+="  退款："+CommonFunction.spellRefundStateWord(refundSate);
        }
        zj.orderState.setText(stateWords);
        zj.picList.setAdapter(new ProductListAdapter(context,ordersJA.getJSONObject(selectID).getJSONArray("products")));
        zj.see.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				System.out.println("to OrderDetailAct order id="+ordersJA.getJSONObject(selectID).getLong(Order.ID));
				Intent intent= new Intent(getActivity(), OrderDetailAct.class);
				intent.putExtra("orderJO", ordersJA.getJSONObject(selectID).toString());
			    startActivity(intent);
			}
		});
        
        return convertView;
       } 
  }// end Adapter
   class ProductListAdapter extends BaseAdapter {
	   
		
	    private LayoutInflater layoutInflater;  
	    private Context context;  
	    private JSONArray productsJA;
	    
	   public ProductListAdapter(Context context, JSONArray productsJA) {
			super();
			
			this.context = context;
		    this.layoutInflater=LayoutInflater.from(context); 
		    this.productsJA= productsJA;
		}


	  final class Zujian{  
	   ImageView img;
	   TextView  product;
	  }   //end of Zujian

	      @Override 
	    public int getCount() {
		// TODO Auto-generated method stub
		
		 return productsJA.size();  
	}

	   @Override
	  public Object getItem(int position) {
		// TODO Auto-generated method stub
		 return productsJA.getJSONObject(position);  
	}

	  @Override
	  public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position; 
	}

	  @Override
	  public View getView(int position, View  convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final int selectID = position;   
		 Zujian zj=null;  
	        if(convertView==null){  
	            zj=new Zujian();  
	            //获得组件，实例化组件  
	            convertView=layoutInflater.inflate(R.layout.list_product_list_order, null);  
	            zj.img= (ImageView) convertView.findViewById(R.id.img_listproduct_listorder);
	            zj.product= (TextView) convertView.findViewById(R.id.tv_product_listproduct_listorder);
	            convertView.setTag(zj);  
	            System.out.println("position----"+selectID+"------inflated");
	        }else{   System.out.println("position----"+selectID+"-------not inflated");
	            zj=(Zujian)convertView.getTag();  
	        }  			  
	        //绑定数据  
	        imageLoader.showImageAsyn(zj.img, productsJA.getJSONObject(selectID).getString(OrderProduct.DIR), R.drawable.p3); 
	        String intro= //productsJA.getJSONObject(selectID).getString(OrderProduct.PRODUCTNAME)
	        //		+"  "+productsJA.getJSONObject(selectID).getString(OrderProduct.BRANCHNAME)
	        		"X"+productsJA.getJSONObject(selectID).getInt(OrderProduct.BRANCHNUM);
	        zj.product.setText(intro);
	        return convertView;
	       } 
	  }// end Adapter
   private  class HttpPostTaskforPollLatestOrder extends android.os.AsyncTask<String,String,Map<String,Object>>{

		

		@Override
		protected Map<String,Object> doInBackground(String... params) {
			// TODO Auto-generated method stub
			 Map<String,Object> map = new HashMap<String ,Object>();		
		  map =	UniversalHttpPost.doPost(params);	             
			return map;
		}
		
		@Override
		protected void onPostExecute(Map<String,Object> map) {
		
			 progres.setVisibility(View.GONE);	
		/*	 Message msg= new Message();
			 msg.what=1;
		    CustomerMainActivity.mainHandler.sendMessage(msg); 
			  */
			 System.out.println("-----------onPostExecute()--------------");
			 String PostResult=(String) map.get("PostResult");		 
			 boolean networkstate=(Boolean) map.get("PostState");
			 if(!networkstate){
				  lt_pullfailed.setVisibility(View.VISIBLE);
				  pull_result.setText("无法连接服务器");
		               return;
			}
			//	Toast.makeText(getActivity(), "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
				Boolean ActionStatus=false;
				String ErrorInfo="";
				JSONObject json = null;
				
				try{
			     json= JSONObject.fromObject(PostResult);
				 ActionStatus=json.getBoolean("success");
				 ErrorInfo=json.getString("errorInfo");					
				}catch(JSONException e){
					 lt_pullfailed.setVisibility(View.VISIBLE);
					  pull_result.setText("数据解析错误");
					  return;
				}
				
				
		       if(!ActionStatus){
	            	 lt_pullfailed.setVisibility(View.VISIBLE);
	            	 pull_result.setText(ErrorInfo); 
	            	 return;
	             } 
		         
		    	    //拉取一次就不再拉取
		    	     needPullOrder=false;
		    	     ordersJA= json.getJSONArray("orders");			  
							 lt_pullfailed.setVisibility(View.GONE);
						     orderList.setVisibility(View.VISIBLE);
							
							 System.out.println("after search   ordersJA.size()="+ ordersJA.size());
						
						 //    myListAdapter.notifyDataSetChanged(); 
							 
						    	 		    	   
		    	     	
			 
		} //onPostExecute
} //AsyncTask
 

	@Override
	public void onHiddenChanged(boolean hidden) {
		// TODO Auto-generated method stub
		if(hidden){ needPullOrder=true;
		}else{
			pull_order();
		}
		
		super.onHiddenChanged(hidden);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		getActivity().unregisterReceiver(broadcastReceiver);  
		super.onDestroy();
	}
}
